<?php

namespace app\common\model;

use app\common\service\StatusService;
use think\Db;
use think\Model;


class Promoter extends Model
{

    

    

    // 表名
    protected $name = 'promoter';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text',
	    'status_text'
    ];
    
	public function getStatusTextAttr($value, $data) {
		$value = $value ? : $data['status'];
		$list = StatusService::$promoterStatusList;
		return $list[$value] ?? '';
	}
	
	
	public function user()
	{
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
	
	/**
	 * 根据用户ID获取正常的推广员
	 * @param $userId
	 * @return array|false|\PDOStatement|string|Model
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function getNormalPromoterByUserId($userId)
	{
		return $this->where([
			'user_id' => $userId,
			'status' => StatusService::STATUS_NORMAL
		])->find();
	}
	
	/**
	 * 获取推广员粉丝数量
	 * @param $userId
	 * @return int|string
	 * @throws \think\Exception
	 */
	public function getPromoterFansNumber($userId)
	{
		return Db::name('user')->where([
			'recommend_id' => $userId,
			'status' => 'normal'
		])->count();
	}
	
	/**
	 * 获取推广员访客数量
	 * @param $userId
	 */
	public function getPromoterVisibleNumber($userId)
	{
		return Db::name('visitor')
			->where(['share_user_id' => $userId])
			->group('user_id')
			->count();
	}
	
	protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


}
